<template>
  <div class="stock-in-list">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="入库单号">
            <el-input v-model="searchForm.stockInCode" placeholder="请输入入库单号" clearable />
          </el-form-item>
          <el-form-item label="仓库">
            <el-select v-model="searchForm.warehouseId" placeholder="请选择仓库" clearable style="width: 100px">
              <el-option v-for="item in warehouseList" :key="item.id" :label="item.warehouseName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="入库类型">
            <el-select v-model="searchForm.stockInType" placeholder="请选择入库类型" clearable style="width: 100px">
              <el-option label="采购入库" value="PURCHASE" />
              <el-option label="退货入库" value="RETURN" />
              <el-option label="其他入库" value="OTHER" />
            </el-select>
          </el-form-item>
          <el-form-item label="入库时间">
            <el-date-picker v-model="searchForm.dateRange" type="datetimerange" range-separator="至"
              start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm"
              :shortcuts="dateShortcuts" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleCreate">新建入库单</el-button>
      </div>

      <!-- 表格 -->
      <div class="order-list">
        <div v-for="item in tableData" :key="item.id" class="order-item">
          <div class="order-header">
            <div class="order-info">
              <span class="order-code">入库单号：{{ item.stockInCode }}</span>
              <span class="order-date">{{
                formatDateTime(item.stockInDate)
              }}</span>
            </div>
            <div class="order-status">
              <el-tag :type="getStockInTypeTag(item.stockInType)">
                {{ getStockInTypeLabel(item.stockInType) }}
              </el-tag>
            </div>
          </div>

            <el-row class="order-content">
              <!-- 新增商品详情列表 -->
              <el-col :span="16" class="goods-list">
                <div v-for="(good, index) in item.items" :key="index" class="goods-item">
                  <el-image :src="good.imageUrl || defaultImage" :preview-src-list="[good.imageUrl]"
                      class="goods-image" fit="cover">
                      <template #error>
                        <div class="image-placeholder">
                          <el-icon>
                            <Picture />
                          </el-icon>
                        </div>
                      </template>
                    </el-image>
                    <div class="goods-info">
                      <div class="goods-name">商品名称：{{ good.productName }}</div>
                      <div class="goods-spec">规格：{{ good.specifications }}</div>

                    </div>
                    <div class="goods-benjin">
                        本金：¥{{ formatAmount(good.purchasePrice) }}
                    </div>
                    <div class="goods-quantity">
                        数量：{{ good.quantity }} {{ good.unit }}
                      </div>
                    <div class="goods-price">
                      <!-- <div class="unit-price">
                        
                      </div> -->
                      <div class="total-price">
                        小计：¥{{ formatAmount(good.amount) }}
                      </div>
                    </div>
                </div>
              </el-col>
              <el-col :span="2" class="warehouse-info">
                <span>仓库：{{ getWarehouseName(item.warehouseId) }}</span>
              </el-col>
              <el-col :span="4" class="amount-info">
                <span class="amount">入库总金额：¥{{ formatAmount(item.totalAmount) }}</span>
              </el-col>
              <el-col :span="2" class="operations">
                  <el-button type="danger"  @click="handleDelete(item)">删除</el-button>
              </el-col>
          </el-row>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          :total="total" layout="total, sizes, prev, pager, next" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="dialogVisible" title="入库单详情" width="80%">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="入库单号">{{
          detailData.stockInCode
        }}</el-descriptions-item>
        <el-descriptions-item label="仓库">{{
          getWarehouseName(detailData.warehouseId)
        }}</el-descriptions-item>
        <el-descriptions-item label="入库类型">
          <el-tag :type="getStockInTypeTag(detailData.stockInType)">
            {{ getStockInTypeLabel(detailData.stockInType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="经办人">{{
          detailData.operator
        }}</el-descriptions-item>
        <el-descriptions-item label="入库时间">{{
          detailData.stockInDate
        }}</el-descriptions-item>
        <el-descriptions-item label="入库金额">¥{{ formatAmount(detailData.totalAmount) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="3">{{
          detailData.remark
        }}</el-descriptions-item>
      </el-descriptions>

      <el-table :data="detailData.items" border style="margin-top: 20px">
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column label="商品图片" width="100">
          <template #default="{ row }">
            <el-image :src="row.imageUrl" :preview-src-list="[row.imageUrl]" preview-teleported fit="contain"
              style="width: 100%; height: 100%">
              <template #error>
                <div class="image-slot">
                  <el-icon>
                    <Picture />
                  </el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="productCode" label="商品编码" width="120" />
        <el-table-column prop="productName" label="商品名称" width="200" />
        <el-table-column prop="specifications" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="quantity" label="数量" width="100" align="right" />
        <el-table-column prop="purchasePrice" label="进价" style="width: 33%" align="right">
          <template #default="scope">
            ¥{{ formatAmount(scope.row.purchasePrice) }}
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="sellingPrice"
          label="售价"
          style="width: 33%"
          align="right"
        >
          <template #default="scope">
            ¥{{ formatAmount(scope.row.sellingPrice) }}
          </template>
        </el-table-column> -->
        <el-table-column prop="amount" label="金额" style="width: 33%" align="right">
          <template #default="scope">
            ¥{{ formatAmount(scope.row.amount) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, toRaw } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { stockInApi, warehouseApi, productApi } from "../../api";

const router = useRouter();
const warehouseList = ref([]);

// 获取仓库列表
const getWarehouseList = async () => {
  try {
    let { data } = await warehouseApi.getList();
    data = data.records.filter((item) => item.status === 1);
    warehouseList.value = data || [];
  } catch (error) {
    console.error("获取仓库列表失败:", error);
    ElMessage.error("获取仓库列表失败");
  }
};

// 获取仓库名称
const getWarehouseName = (id) => {
  const warehouse = warehouseList.value.find((item) => item.id === id);
  return warehouse ? warehouse.warehouseName : "";
};

// 入库类型配置
const stockInTypes = {
  PURCHASE: { label: "采购入库", type: "success" },
  RETURN: { label: "退货入库", type: "warning" },
  OTHER: { label: "其他入库", type: "info" },
};

const getStockInTypeLabel = (type) => stockInTypes[type]?.label || type;
const getStockInTypeTag = (type) => stockInTypes[type]?.type || "";

// 搜索表单
const searchForm = reactive({
  stockInCode: "",
  warehouseId: "",
  stockInType: "",
  dateRange: [],
});

// 表格数据
const loading = ref(false);
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      pageSize: pageSize.value,
      stockInCode: searchForm.stockInCode || undefined,
      warehouseId: searchForm.warehouseId || undefined,
      stockInType: searchForm.stockInType || undefined,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1],
    };

    const { data } = await stockInApi.getList(params);
    tableData.value = data.records;
    tableData.value.forEach(item => {
      item.items.forEach(item => {
        item.imageUrl = import.meta.env.VITE_API_URL + item.imageUrl
      })
    })
    console.log(tableData.value, "tableData.value");
    total.value = data.total;

    // 获取每条记录的明细数据
    // for (const row of tableData.value) {
    //   if (row.items) {
    //     const productIds = row.items.map((item) => item.productId);
    //     const { data: products } = await productApi.getByIds(productIds);

    //     // 将商品信息添加到items中
    //     row.items = row.items.map((item) => {
    //       const product = products.find((p) => p.id === item.productId);
    //       return {
    //         ...item,
    //         productCode: product?.productCode,
    //         productName: product?.productName,
    //         specifications: product?.specifications,
    //         unit: product?.unit,
    //         purchasePrice: product?.purchasePrice,
    //         // sellingPrice: product?.sellingPrice,
    //       };
    //     });
    //   }
    // }
  } catch (error) {
    console.error("获取数据失败:", error);
    ElMessage.error(error.message || "获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getTableData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.stockInCode = "";
  searchForm.warehouseId = "";
  searchForm.stockInType = "";
  searchForm.dateRange = [];
  handleSearch();
};

// 新建入库单
const handleCreate = () => {
  router.push("/stock-in/create");
};

// 查看详情
const dialogVisible = ref(false);
const detailData = ref({});

// const handleView = async (row) => {
//   try {
//     const data = tableData.value.find((item) => item.id === row.id);
//     if (data.items) {
//       const productIds = data.items.map((item) => item.productId);
//       const { data: products } = await productApi.getByIds(productIds);

//       // 将商品信息添加到items中
//       data.items = data.items.map((item) => {
//         const product = products.find((p) => p.id === item.productId);
//         return {
//           ...item,
//           productCode: product?.productCode,
//           productName: product?.productName,
//           specifications: product?.specifications,
//           purchasePrice: product?.purchasePrice,
//           unit: product?.unit,
//           imageUrl: import.meta.env.VITE_API_URL + product?.imageUrl,
//         };
//       });
//     }
//     detailData.value = data;
//     dialogVisible.value = true;
//   } catch (error) {
//     console.error("获取详情失败:", error);
//     ElMessage.error(error.message || "获取详情失败");
//   }
// };

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm("确认删除该入库单吗？", "提示", {
      type: "warning",
    });

    await stockInApi.delete(row.id);
    ElMessage.success("删除成功");
    getTableData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error(error.message || "删除失败");
    }
  }
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  getTableData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getTableData();
};

// 格式化金额
const formatAmount = (amount) => {
  if (amount === undefined || amount === null || isNaN(amount)) {
    return "0.00";
  }
  return Number(amount).toFixed(2);
};

// 添加时间格式化方法
const formatDateTime = (datetime) => {
  if (!datetime) return "";
  return datetime.replace("T", " ");
};

// 修改日期快捷选项
const dateShortcuts = [
  {
    text: "最近24小时",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24);
      return [start, end];
    },
  },
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 初始化
onMounted(async () => {
  await getWarehouseList();
  getTableData();
});
</script>

<style lang="scss" scoped>
.stock-in-list {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-area {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.order-list {
  .order-item {
    background: #fff;
    border-radius: 4px;
    margin-bottom: 16px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    .order-header {
      padding: 16px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .order-info {
        .order-code {
          font-weight: bold;
          margin-right: 24px;
        }
        .order-date {
          color: #999;
        }
      }
    }
    .order-content {
      padding: 16px;
      
      .amount-info {
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1px solid #f0f0f0;
        padding: 16px 0;
        margin: 16px 0;
        .amount {
          font-size: 16px;
          color: #f56c6c;
          font-weight: bold;
          
        }
      }
    }
  }
}
.operations {
          display: flex;
          justify-content: center;
          align-items: center;
          gap: 8px;
          border: 1px solid #f0f0f0;
          padding: 16px 0;
          margin: 16px 0;
          border-left: none;
        }
.warehouse-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin: 16px 0;
  padding: 16px 0;
  border: 1px solid #f0f0f0;
  border-right: none;
  box-sizing: border-box;
  color: #666;
  font-size: 14px;
  text-align: center;
  .operator {
    margin-top: 16px;
    margin-left: 24px;
  }
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.goods-list {
  margin: 16px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 20px;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 12px 0;

  &:not(:last-child) {
    border-bottom: 1px dashed #f0f0f0;
  }
}

.goods-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 16px;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
  color: #909399;
}

.goods-info {
  flex: 1;

  .goods-name {
    font-weight: bold;
    margin-bottom: 8px;
  }

  .goods-spec,
  .goods-quantity {
    color: #666;
    font-size: 14px;
    margin-bottom: 4px;
  }
  
}
.goods-benjin {
    text-align: center;
    min-width: 150px;
    color: #666;  
    font-size: 14px;
  }
.goods-price {
  text-align: right;
  min-width: 150px;

  .unit-price {
    color: #666;
    font-size: 14px;
    margin-bottom: 4px;
  }

  .total-price {
    color: #f56c6c;
    font-weight: bold;
  }
}
</style>